﻿using UnityEngine;
using System.Collections;


public class Battle5vs5Center : MonoBehaviour {

	private static Battle5vs5Center instance;
	
	public static Battle5vs5Center Instance{
		get{
			return instance;
		}
	}	

	public int MAXLINE=6;
	public int MAXLINE_HALF=3;
	public int MAXROW=5;
	public int ROWCENTER=2;

	public float gapFromCenter=1.0f;
	public float gapBetweenLine=2.0f;
	public float gapBetweenRow=2.0f;
	public float offsetSideRow1=0.2f;
	public float offsetSideRow2=0.4f;

	new public Transform transform;
	//public GameObject[,] positionGo;
	public Vector3 [,] positionVec;
	public bool[,] isOccupied;
	public BattlePawn[,] pawns;
	int [] fillSeq;

	void Awake()
	{
		fillSeq = new int[5]{2,3,1,4,0};
		instance = this;
		//positionGo = new GameObject[MAXLINE,MAXROW];
		positionVec = new Vector3[MAXLINE,MAXROW];
		isOccupied = new bool[MAXLINE,MAXROW];
		pawns = new BattlePawn[MAXLINE,MAXROW];
		transform = gameObject.transform;
		for(int line = 0; line<MAXLINE; line++) {
			for(int row = 0; row<MAXROW; row++) {
				//positionGo[line,row] = new GameObject();
				//positionGo[line,row].name = string.Format("{0}_{1}",line,row);
				Vector3 newPos = transform.position;
				if(line<MAXLINE_HALF) {
					newPos.x += gapFromCenter;
					newPos.x += (MAXLINE_HALF-line-1)*gapBetweenLine;
					if(row==1 || row==3)
						newPos.x -= offsetSideRow1;
					else if(row==0 || row==4)
						newPos.x -= offsetSideRow2;
				}
				else {
					newPos.x -= gapFromCenter;
					newPos.x -= (line-MAXLINE_HALF)*gapBetweenLine;
					if(row==1 || row==3)
						newPos.x += offsetSideRow1;
					else if(row==0 || row==4)
						newPos.x += offsetSideRow2;
				}
				if(row<ROWCENTER)
					newPos.z -= (ROWCENTER-row)*gapBetweenRow;
				else if(row>ROWCENTER)
					newPos.z += (row-ROWCENTER)*gapBetweenRow;
				//positionGo[line,row].transform.position = newPos;
				positionVec[line,row] = newPos;
			}
		}
	}

	public int SetPos(BattlePawn _pawn, Transform _trans, bool isPlayer, int nLine)
	{
		int nRow=0;
		bool isRepresent=true;
		for(int i=0; i< 5; i++) {
			nRow = fillSeq[i];
			if(!isOccupied[nLine,nRow]) {
				isOccupied[nLine,nRow]=true;
				break;
			}
			else
				isRepresent=false;
		}
		pawns[nLine,nRow] = _pawn;
		_pawn.isRepresent=isRepresent;
		_trans.position = positionVec[nLine,nRow];//positionGo[nLine,nRow].transform.position;
		if(isPlayer)
			_trans.rotation = Quaternion.Euler(0, -90, 0);
		else
			_trans.rotation = Quaternion.Euler(0, 90, 0);
		return nRow;
	}
	
	public void SetOccupied(BattlePawn pawn, bool bSet)
	{
		isOccupied[pawn.myCurLine,pawn.myRow]=bSet;
		if(!bSet)
			pawns[pawn.myCurLine,pawn.myRow] = null;
		else
			pawns[pawn.myCurLine,pawn.myRow]=pawn;
	}

	public void ClearAllOccupy()
	{
		for(int line = 0; line<MAXLINE; line++) {
			for(int row = 0; row<MAXROW; row++) {
				pawns[line, row] = null;
				isOccupied[line, row]=false;
			}
		}
	}
}
